import getpath
import os
import openpyxl
from openpyxl.drawing.image import Image
import fitz
from pprint import pprint
from PyQt5 import QtWidgets
import fitz
import io
from PIL import Image as PILImage
from typing import Tuple
doc=None
curvePage=-1
def getimages(pages: Tuple = None):
    """Converts pdf to image and generates a file by page"""
    # Open the document
    pimgs = []
    # Iterate throughout the pages
    for pg in range(doc.page_count):
        if str(pages) != str(None):
            if str(pg) not in str(pages):
                continue
        # Select a page
        page = doc[pg]
        pix = page.get_pixmap()#matrix=mat, alpha=False)
        # mode="RGBA" if pix.alpha else "RGB"
        # img=Image.frombytes(mode,[pix.width,pix.height],pix.samples)
        # print(img,type(img))
        # mode = "RGBA" if pix.alpha else "RGB"
        # img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
        bs=pix.tobytes() #openpyxl need fp 
        img=PILImage.open(io.BytesIO(bs))
        pimgs.append(img)
    return pimgs
def T(a):
    b=[]
    for i in range(len(a[0])):
        b.append([])
    for i in range(len(a)):
        one=a[i]
        for j in range(len(one)):#cell in one:
            b[j].append(one[j])
    return b
def addOne(data,one):
    if len(data)==0:#first
        r=one
    else:
        r=np.concatenate((data,one),axis=1)
    return r
 
def addOneAxis0(data,one):
    if len(data)==0:#first
        r=one
    else:
        r=data+one[1:]#remove first title row
    return r    
def getDataMass(file_name):
    global doc,curvePage
    doc=fitz.open(file_name) # open document
    data=[]
    mass=[]
    tables=[]
    for i in range(doc.page_count).__reversed__():
        page = doc[i]
        tabs=page.find_tables()
        if len(tabs.tables)==0:
            break
        else:
            tables.append(tabs[0].extract())
    tables.reverse()
    for one in tables:
        if one[0][0]=="溶液标签":
            data=addOneAxis0(data,T(one))#data.append(one)
        else:
            mass=addOneAxis0(mass,one)
    curvePage=i
    return (T(data),mass)
def mergeMass(data,mass):
    data[0].append("mass")
    data[0].append("volume")
    for one in data[1:]:
        (m,volume)=getMass(one[0],mass)
        one.append(m)
        one.append(volume)
    return data
def selectMass(data,mass):
    r=[("mass","volume")]
    for one in data[1:]:
        (m,volume)=getMass(one[0],mass)
        r.append((m,volume))
    return r

def getMass(one,mass):
    one=one.replace("\n","")
    for m in mass:
        if len(m)>3 and  m[1]==one:
            return (m[2],float(m[3])*100)
    return ("","")
def output(ts,fname):
    f=open(fname,'w')
    for one in ts:
        line=",".join(one)
        line=line.replace("\n","")
        f.write(line+"\n")
    f.close()
def getDataAndMass(fname):
    (data,mass)=getDataMass(fname)
    mass=selectMass(data,mass)
    return (data,mass)
# def total(fname):
#     (data,mass,i)=getDataAndMass(fname)
#     output_files=getimages.convert_pdf2img(fname,list(range(i+1)))
#     wb = openpyxl.Workbook()
#     ws = wb.active
#     # output_files=["ajl_page1.png","ajl_page2.png"]
#     # imgsize = (720 / 4, 1280 / 4)  # 设置一个图像缩小的比例
#     # ws.column_dimensions['A'].width =720  # 修改列A的宽
#     for i in range(len(output_files)):
#         img = Image(output_files[i])  # 缩放图片
#         print(type(img),dir(img))
#         return 
#         # img.width, img.height = imgsize
#         ws.column_dimensions['A'].width =img.width* 0.14
#         ws.row_dimensions[str(i+1)].height =img.height* 0.78
#         ws.add_image(img, 'A'+str(i+1))  # 图片 插入 A1 的位置上
#         # ws.row_dimensions[str(i+1)].height = 720  # 修改列第1行的宽
#     wb.save('out.xlsx')  # 新的结果保存输出
def output_curve(ws,hang):#outputsheet,pdf filename,0-n page
    imgs=getimages(list(range(curvePage +1)))
    outputImages(imgs,ws,hang)
def outputImages(imgs,ws,hang):#outputsheet,pdf filename,0-n page
    rowh=13.5/72.0*QtWidgets.qApp.screens()[0].physicalDotsPerInch() #bang to pixel
    for i in range(len(imgs)):
        img = Image(imgs[i])#Image(output_files[i])  # 缩放图片
        n=int((img.height)/rowh)
        at_row=i*n+hang
        ws.add_image(img, "A"+str(at_row))  # 图片 插入 A1 的位置上
def test1():
    (data,mass,i)=getDataAndMass("ajl.pdf")
    print(data)
    print(mass)
    print(i)
    # output(mass,"mass_m.csv")
def geti():
    wb = openpyxl.Workbook()
    ws = wb.active
    outputImages(ws,"ajl.pdf",16)
    wb.save("out.xlsx")
if __name__=="__main__":
    test1()
